let db              = require('../db/dbmanager');
const deviceCache = require("../db/deviceCache");
const log4js        = require('../utils/logUtils');
const logger        = log4js.getLogger('model');

/**
 * 设备表操作
 */
let Device = {
    cache: null,
    /**
     * 插入数据
     * @param {*} data ["testdevice",false]
     */
    insert(data){
        return new Promise(function(resolve, reject){
            if(!data.deviceid){
                reject(null);
            }else {
                let param = {
                    $deviceid: data.deviceid,
                    $password: data.password,
                    $online: data.online,
                    $last_heart: (new Date()).getTime()
                };
                const sql = "insert into DEVICE(deviceid,password,online,last_heart) values($deviceid,$password,$online,$last_heart)";

                db.sqliteDB.run(sql, param);
                Device.cache = null;
                db.sqliteDB.lastRow("DEVICE", (d) => {
                    resolve(d);
                });
            }
        });
    },
    /**
     * 更新内容,newdata的属性有; online,deviceid,sip_command_host,sip_command_port,sumnum,version,device_type,last_heart
     * @param {*} updateData
     */
    update(updateData){
        return new Promise(function(resolve){
            let sqldata={
                $deviceid: updateData.deviceid
            };

            let newsql='';
            if(updateData.online){
                sqldata.$online = updateData.online;
                if(newsql)newsql+=',';
                newsql += "online=$online";
            }
            if(updateData.sip_command_host){
                sqldata.$sip_command_host = updateData.sip_command_host;
                if(newsql)newsql+=',';
                newsql += "sip_command_host=$sip_command_host";
            }
            if(updateData.sip_command_port){
                sqldata.$sip_command_port = updateData.sip_command_port;
                if(newsql)newsql+=',';
                newsql += "sip_command_port=$sip_command_port";
            }
            if(updateData.sumnum){
                sqldata.$sumnum = updateData.sumnum;
                if(newsql)newsql+=',';
                newsql += "sumnum=$sumnum";
            }
            if(updateData.version){
                sqldata.$version = updateData.version;
                if(newsql)newsql+=',';
                newsql += "version=$version";
            }
            if(updateData.device_type){
                sqldata.$device_type = updateData.device_type;
                if(newsql)newsql+=',';
                newsql += "device_type=$device_type";
            }

            if(updateData.device_name){
                sqldata.$device_name = updateData.device_name;
                if(newsql)newsql+=',';
                newsql += "device_name=$device_name";
            }
            if(updateData.last_heart){
                sqldata.$last_heart=updateData.last_heart;
                if(newsql)newsql+=',';
                newsql += "last_heart=$last_heart";
            }
            if(updateData.server_id){
                sqldata.$server_id=updateData.server_id;
                if(newsql)newsql+=',';
                newsql += "server_id=$server_id";
            }
            if(updateData.rtsp_url){
                sqldata.$rtsp_url=updateData.rtsp_url;
                if(newsql)newsql+=',';
                newsql += "rtsp_url=$rtsp_url";
            }
            if(updateData.protocol){
                sqldata.$protocol=updateData.protocol;
                if(newsql)newsql+=',';
                newsql += "protocol=$protocol";
            }
            const sql = "update DEVICE set " + newsql + " where deviceid=$deviceid";

            db.sqliteDB.run(sql,sqldata);
            // logger.info('[更新device]', sql);
            Device.cache = null;
            resolve(updateData);
        });
    },
    /**
     * 删除设备信息，同时删除子通道
     */
    del(deviceid){
        let param={
            $deviceid: deviceid
        };
        const sql = "DELETE FROM DEVICE WHERE deviceid=$deviceid";
        db.sqliteDB.run(sql,param);
        const sqlChannel="DELETE FROM CHANNEL WHERE parentid = $parentid";
        let paramChannel = {$parentid: deviceid};
        db.sqliteDB.run(sqlChannel,paramChannel);
        Device.cache = null;
    },
    /**
     *
     * @param {string} deviceid 通道号
     */
    async getDeviceByDeviceId(deviceid){
        if(!Device.cache){
            await Device.reloadCache();
        }
        return new Promise(function (resolve) {
            let item = Device.cache.find((value) => {return value.deviceid === deviceid});
            if(item && item.sip_command_host){
                item.sip_command_host = item.sip_command_host.replace("::ffff:", "");
            }
            resolve(item);
        });
    },
    /**
     * 设备设置的在线状态
     * @param {*} deviceid
     * @param online 设备是否在线
     */
    async register(deviceid, online) {
        return new Promise(async function (resolve) {
            let ret = await Device.getDeviceByDeviceId(deviceid);
            deviceCache.registry[deviceid].online = online;
            if (online) {
                deviceCache.registry[deviceid].last_heart = (new Date()).getTime();
            }

            if (ret) {
                await Device.update(deviceCache.registry[deviceid]);
            } else {
                await Device.insert(deviceCache.registry[deviceid]);
            }
            Device.cache = null;
            resolve(deviceid);
        });
    },
    reloadCache(){
        return new Promise(function (resolve) {
            if (!Device.cache) {
                const sql = "SELECT * from DEVICE order by deviceid DESC";
                db.sqliteDB.queryData(sql, function (rows) {
                    Device.cache = Object.assign(rows);
                    resolve(Device.cache);
                });
            } else {
                resolve(Device.cache);
            }
        });
    },
    /**
     * 查询列表
     * @param {*} page 第几页
     * @param {*} size 每页大小
     * @param deviceId
     */
    list(page, size, deviceId){
        return new Promise(function (resolve) {
            let sql = "SELECT * FROM DEVICE ";
            let data;
            if (deviceId) {
                sql += " WHERE deviceid LIKE ? OR device_name LIKE ?";
                data = [`%${deviceId}%`, `%${deviceId}%`,];
            } else {
                data = [];
            }
            sql += ` order by deviceid DESC limit ${size} offset ${size}*${page}`;
            db.sqliteDB.all(sql, data, function (err, rows) {
                resolve(rows);
            });
        });
    },
    count(device){
        return new Promise(function (resolve) {
            let sql = "SELECT COUNT(*) as c FROM DEVICE ";
            let data;
            if (device) {
                sql += " WHERE deviceid LIKE ? OR device_name LIKE ?";
                data = ['%' + device + '%', '%' + device + '%',];
            } else {
                data = [];
            }
            db.sqliteDB.all(sql, data, (err, ret) => {
                if(ret && ret.length>0) {
                    resolve(ret[0].c)
                }else{
                    resolve(0);
                }
            });
        });
    },
    // TODO: 重置状态，device的可能要修改
    reset(){
        // 60分钟没收到消息的
        let minTime = (new Date()).getTime()-60*10*1000;
        let sql = "UPDATE DEVICE SET online=0 WHERE last_heart < " + minTime;

        db.sqliteDB.run(sql);
        Device.cache = null;
    },
    /**
     * 从 device 上生成新 channel 信息
     * @returns {*}
     */
    generateEmptyChannel(deviceInfo, channelId){
        let channel = Object.assign({}, deviceInfo);
        // 删除三个不用的属性
        delete channel['channels'];
        delete channel['sip_command_host'];
        delete channel['sip_command_port'];

        channel.deviceid = channelId;
        return channel;
    }
};

module.exports = Device;
